jQuery(document).ready(function($) {
	  var elem = document.getElementById('sonna_search');
	  if(elem == undefined){
		log('nessun elemento sonna_search trovato');
		return;
	  }
	  elem.innerHTML = '<div style="display: block"><div><span>Search with google: </span><input type="text" name="google_search" id="google_search" onkeydown="checkKey(event, this.id);"/><input type="button" name="google_search_btn" id="google_search_btn" value="Search" onclick="googleSearch();"/></div><div><span>Search with wikipedia: </span><input type="text" name="wiki_search" id="wiki_search" onkeydown="checkKey(event, this.id);"/><input type="button" name="wiki_search_btn" id="wiki_search_btn" value="Search" onclick="wikiSearch();"/></div>	</div>';
 });

function googleSearch(){
	if(!_fb_user.isLogged()){
		alert('Please login with your Facebook account first');
		return;
	}

	var elem_text = document.getElementById('google_search');
	var text = escape(elem_text.value);
	window.open('http://www.google.it/#hl=it&output=search&q=' + text, '_blank');
	saveSearch(_fb_user.getUserId(), 'google', text);
}

function wikiSearch(){
	if(!_fb_user.isLogged()){
		alert('Please login with your Facebook account first');
		return;
	}

	var elem_text = document.getElementById('wiki_search');
	var text = escape(elem_text.value);
	window.open('http://it.wikipedia.org/w/index.php?search=' + text, '_blank');
	saveSearch(_fb_user.getUserId(), 'wikipedia', text);				
}

function checkKey(event, name){
	if (event.keyCode == 13)
		document.getElementById(name + '_btn').click();
}

function tempSuccess(result){
	log('L\'utente è stato inserito correttamente nel db');	
}

function tempFailure(result){
	log('c\' stato qualche problema!');	
}	

function saveSearch(userId, engine, search){
	var req = new Request();
	req.setOnSuccess(tempSuccess);
	req.setOnFailure(tempFailure);
	var params = new Object();
	params.uid = userId;
	params.engine = engine;
	params.search = search;
	req.asyncPostRequest(getRestUrl() + 'user/search', JSON.stringify(params));
}

